package com.marktotop.controller;


import com.marktotop.pojo.Payment;
import com.marktotop.response.ResultBean;
import com.marktotop.service.IPaymentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author MarkToTop
 * @since 2021-07-03
 */
@RestController
@Slf4j
@RequestMapping("/payment")
@Api(tags = "支付订单号接口")
public class PaymentController {

    @Autowired
    private IPaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    /**
     * 导入 org.springframework.cloud.client.discovery.DiscoveryClient;
     */
    @Autowired
    private DiscoveryClient discoveryClient;

    /**
     * 创建流水号
     * @param payment
     * @return
     */
    @ApiOperation(value = "创建流水号")
    @RequestMapping(value = "/create",method = RequestMethod.POST)
    public ResultBean createPayment(@RequestBody Payment payment){
        if (paymentService.save(payment)){
//            log.info("****插入payment成功！");
            return ResultBean.ok().message("创建流水号操作成功!serverPort:"+serverPort);
        }
        return ResultBean.error().message("创建流水号失败!");
    }

    /**
     * 根据id查询流水号
     * @param id
     * @return
     */
    @ApiOperation(value = "根据id查询流水号")
    @RequestMapping(value = "/get/{id}",method = RequestMethod.GET)
    public ResultBean getPaymentById(@PathVariable("id") Long id){
        Payment paymentById = paymentService.getById(id);
        if (null == paymentById){
            return ResultBean.error().message("查询流水号失败，查询ID:"+id);
        }
        return ResultBean.ok().message("查询流水号处理成功!serverPort:"+serverPort).data("result",paymentById);
    }

    /**
     * 服务发现
     * @return
     */
    @ApiOperation(value = "服务发现")
    @RequestMapping(value = "/discovery",method = RequestMethod.GET)
    public Object discovery(){
        List<String> services = discoveryClient.getServices();
        for (String element : services) {
            log.info("****element:"+element);
        }

        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");

        for (ServiceInstance instance : instances) {
            log.info(instance.getServiceId()+"\t"+instance.getHost()+"\t"+instance.getPort()+"\t"+instance.getUri());
        }
        return this.discoveryClient;
    }

}
